<?php
class Online_Ebay_Product extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
			    # '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'online_ebay_product',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	

	/**
	 * 批量导入ebay产品描述信息
	 * @param $info 信息数组
	 * $type : update / only_insert
	 */
	static function import($product_info, $type = '')
	{
		$language_message = '';
		$product_message = '';
		foreach ($product_info as $pi)
		{
			$language = Helper_BSS_Normal::getIniOne('online_ebay_product_language', 'text', $pi['language'], 'value');
			if ($language)
			{
				$product_basic_number = str_pad($pi['SKU'], '6', '0', STR_PAD_LEFT);
				$product_basic_number = substr($product_basic_number, 0, 6);
				$product_basic = Product_Basic::find('number=?', $product_basic_number)->asArray()->getOne();
				if ($product_basic)
				{
					$result = Online_Ebay_Product::find('product_basic_id=? and language=?', $product_basic['id'], $language)->asArray()->getOne();
					if ($result)
					{
						$online_ebay_product = Online_Ebay_Product::find('id=?', $result['id'])->getOne();
					}
					else
					{
						$online_ebay_product = new Online_Ebay_Product();
						$online_ebay_product->product_basic_id = $product_basic['id'];
						$online_ebay_product->language = $language;
					}
					if ($type != 'only_insert' || ! $result)
					{
						$online_ebay_product->title = $pi['Item_Title'];
						$online_ebay_product->description = $pi['Description'];
						$online_ebay_product->upload_files_id = $pi['file_id'];
						$online_ebay_product->update_time = CURRENT_DATETIME;
						$online_ebay_product->update_user_id = CURRENT_USER_ID ? CURRENT_USER_ID : 0;
						$online_ebay_product->save();
					}
				}
				else
				{
					$product_message = "部分产品不存在;";
				}
			}
			else
			{
				$language_message = "部分产品语种不正确;";
			}
		}
		if ($language_message || $product_message)
		{
			return array('ack' => FAILURE, 'message' => $product_message . $language_message);
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	/*
	 * 定期更新 ebay 的产品描述信息
	 * $shop_id ebay 的店铺id
	 * $start_time 开始时间
	 * $end_time 结束时间
	 * $type up / down 上架 / 下架
	 */
	static function getEbayProductListing($shop_id, $start_time, $end_time, $type)
	{
		$token = Shop_API_Ebay::find('shop_id=?', $shop_id)->asArray()->getOne();
		$shop_listings = array();
		if ($token && $start_time && $end_time && $type)
		{
			$ps = 10;
			$cp = 0;
			$total_entries = 1;
			$listings = array();
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:0',
				'X-EBAY-API-CALL-NAME:GetSellerList'
			);
			while ($ps * $cp < $total_entries)
			{
				$cp++;
				$xml = '<?xml version="1.0" encoding="utf-8"?>';
				$xml .= '<GetSellerListRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
				$xml .= '<RequesterCredentials>';
				$xml .= '<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
				$xml .= '</RequesterCredentials>';
				$xml .= '<ErrorLanguage>en_US</ErrorLanguage>';
				$xml .= '<DetailLevel>ReturnAll</DetailLevel>';
				$xml .= '<IncludeWatchCount>true</IncludeWatchCount>';
				if ($type == 'up')
				{
					$xml .='<StartTimeFrom>' . $start_time . '</StartTimeFrom>';
					$xml .='<StartTimeTo>' . $end_time . '</StartTimeTo>';
				}
				else
				{
					$xml .='<EndTimeFrom>' . $start_time . '</EndTimeFrom>';
					$xml .='<EndTimeTo>' . $end_time . '</EndTimeTo> ';
				}
				$xml .= '<IncludeVariations>true</IncludeVariations>';
				$xml .= '<Pagination> ';
				$xml .= '<EntriesPerPage>' . $ps . '</EntriesPerPage>';
				$xml .= '<PageNumber>' . $cp . '</PageNumber>';
				$xml .= '</Pagination>';
				$xml .= '<OutputSelector>ItemArray.Item.title</OutputSelector>';
				$xml .= '<OutputSelector>ItemArray.Item.site</OutputSelector>';
				$xml .= '<OutputSelector>ItemArray.Item.Description</OutputSelector>';
				$xml .= '<OutputSelector>ItemArray.Item.SKU</OutputSelector>';
				$xml .= '<OutputSelector>ItemArray.Item.Variations.Variation.SKU</OutputSelector>';
				$xml .= '<OutputSelector>PaginationResult</OutputSelector>';
				$xml .= '<OutputSelector>ReturnedItemCountActual</OutputSelector>';
				$xml .= '</GetSellerListRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'GetSellerList', $cp);
				if ($result['ack'] == SUCCESS)
				{
					$response = simplexml_load_string($result['data']);
					if ($response && $response->Ack == 'Success')
					{
						$total_entries = (string)$response->PaginationResult[0]->TotalNumberOfEntries[0];
						foreach ($response->ItemArray[0]->Item as $ri)
						{
							$site = (string)$ri->Site[0];
							$language = Q::ini('custom_flag/online_ebay_product_site_language/' . $site . '/value');
							if ( ! empty($language))
							{
								$listing = array();
								$listing['Item_Title'] = (string)$ri->Title[0];
								$listing['Description'] = (string)$ri->Description[0];
								$listing['language'] = $language;
								$listing['file_id'] = 0;
								if (isset($ri->Variations[0]))
								{
									foreach ($ri->Variations[0]->Variation as $riv)
									{
										$listing['SKU'] = (string)$riv->SKU[0];
										$listings[] = $listing;
									}
								}
								else
								{
									$listing['SKU'] = (string)$ri->SKU[0];
									$listings[] = $listing;
								}
							}
						}
					}
				}
				else
				{
					return array('ack' => FAILURE, 'message' => $result['message']);
				}
			}
			return array('ack' => SUCCESS, 'message' => '', 'data' => $listings);
		}
		else
		{
			return array('ack' => FAILURE, 'message' => ' token 码不存在或 getEbayProductListing 参数不完整;');
		}
	}
	
	static function editSave($product_info)
	{
		$product_info->language = $_POST['language'];
		$product_info->title = $_POST['title'];
		$product_info->description = $_POST['description'];
		$product_info->update_time = CURRENT_DATETIME;
		$product_info->update_user_id = CURRENT_USER_ID;
		$product_info->save();	
		return array('ack' => SUCCESS, 'message' => '');	
	}
	
	static function search($condition, $cp, $ps)
	{
		$columns = array(
			'online_ebay_product.*',
			'product_basic.number, product_basic.name'
		);
		$where = Online_Ebay_Product::buildSearchWhere($condition);
		if ($cp == 0 && $ps == 0)
		{
			$select = Online_Ebay_Product::find($where)
				->joinleft('product_basic', '', 'product_basic.id=online_ebay_product.product_basic_id')
				->setColumns($columns);
			$pagination = array();
		}
		else
		{
			$select = Online_Ebay_Product::find($where)
				->joinleft('product_basic', '', 'product_basic.id=online_ebay_product.product_basic_id')
				->setColumns($columns)->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$product_info = $select->order('online_ebay_product.update_time desc')->asArray()->getAll();
		return array(
			'ack' => SUCCESS,
			'message' => '',
			'data' => $product_info,
			'pagination' => $pagination
		);
	}
	
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if (! empty($condition['begin_update_time']))
		{
			$where .= ' and online_ebay_product.update_time>=\'' . $condition['begin_update_time'] . '\'';
		}
		if (! empty($condition['end_update_time']))
		{
			$where .= ' and online_ebay_product.update_time<=\'' . $condition['end_update_time'] . ' 23:59:59\'';
		}
		if (! empty($condition['product_number']))
		{
			$product_number = Q::normalize($condition['product_number']);
			$where .= ' and product_basic.number in (\'' . implode('\',\'', $product_number) . '\')';
		}
		if (! empty($condition['file_id']))
		{
			$where .= ' and online_ebay_product.upload_files_id=' . $condition['file_id'];
		}
		if (! empty($condition['product_name']))
		{
			$where .= ' and product_basic.name like \'%' . $condition['product_name'] . '%\'';
		}
		if (! empty($condition['product_categories_id']))
		{
			$product_categories_ids = Product_Categories::getOffspringById($condition['product_categories_id']);
			array_push($product_categories_ids, $condition['product_categories_id']);
			$where .= ' and product_basic.product_categories_id in (' . implode(',', $product_categories_ids) . ')';
		}
		if (! empty($condition['language']))
		{
			$where .= ' and online_ebay_product.language=' . $condition['language'];
		}
		return $where;
	}
}